package com.lenovo.dll.nebula.vod.parse;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

public class SaxXmlParse {

	public <T> List<T> getParseData(ParserHandler<T> handler) {
		if (handler == null) {
			return null;
		}
		SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
		try {
			XMLReader xmlReader = saxParserFactory.newSAXParser()
					.getXMLReader();
			xmlReader.setContentHandler(handler);
			InputStream in = doPost(handler.getParams(), handler.getUrl());
			InputSource source = new InputSource(in);
			xmlReader.parse(source);
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return handler.getDataList();
	}

	private InputStream doPost(Map<String, String> parameters, String strUrl)
			throws IOException {
		InputStream inputStream = null;
		String params = appendParameters(parameters);
		URL url = new URL(strUrl);
		HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
		urlConn.setRequestMethod("POST");
		urlConn.setConnectTimeout(30000);
		urlConn.setReadTimeout(30000);
		urlConn.setDoInput(true);
		urlConn.setDoOutput(true);
		if (params != null) {
			byte[] b = params.getBytes();
			urlConn.getOutputStream().write(b, 0, b.length);
		}
		urlConn.getOutputStream().flush();
		urlConn.getOutputStream().close();
		inputStream = urlConn.getInputStream();
		return inputStream;
	}

	private String appendParameters(Map<String, String> parameters)
			throws UnsupportedEncodingException {
		if (parameters == null || parameters.size() < 1) {
			return null;
		}
		StringBuffer params = new StringBuffer();
		Set<String> keys = parameters.keySet();
		for (String key : keys) {
			params.append(key).append("=")
					.append(URLEncoder.encode(parameters.get(key), "UTF-8"))
					.append("&");
		}
		params.deleteCharAt(params.length() - 1);
		return params.toString();
	}

}
